import { useEffect, useMemo } from 'react';
import { useCall } from '.';

function useSetTimeout() {
  const timers = useMemo(() => [], []);

  const setTimeout = useCall((...args) => {
    const nativeTimer = window.setTimeout(...args);
    timers.push(nativeTimer);
    return () => {
      timers.splice(timers.indexOf(nativeTimer), 1);
      clearTimeout(nativeTimer);
    };
  });

  useEffect(() => {
    return () => {
      for (const timer of timers) clearTimeout(timer);
    };
  }, []);

  return setTimeout;
}

export default useSetTimeout;
